<template>
	<section>
		<!--高级查询工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="changePage">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--部门列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column type="index" width="60"></el-table-column>
			<el-table-column prop="username" label="员工姓名" width="80" sortable></el-table-column>
			<el-table-column prop="email" label="员工邮箱" width="80" sortable></el-table-column>
			<el-table-column prop="phone" label="员工电话" width="80" sortable></el-table-column>
			<el-table-column prop="salt" label="员工盐值" width="80" sortable></el-table-column>
			<el-table-column prop="password" label="员工密码" width="80" sortable></el-table-column>
			<el-table-column prop="age" label="员工年龄" width="80" sortable></el-table-column>
			<el-table-column prop="state" label="员工状态" width="80"sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state===1">在线</span>
					<span style="color: red" v-else-if="scope.row.state===0">离线</span>
					<span style="color: blue" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="department.name" label="所属部门" width="80" sortable></el-table-column>
			<el-table-column prop="shop.name" label="所属公司" width="80" sortable></el-table-column>
			<el-table-column prop="logininfo.type" label="用户身份BUG" width="80"sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.logininfo.type ==true">用户</span>
					<!--<span style="color: red" v-else-if="scope.row.type=false">管理员</span>-->
					<span style="color: blue" v-else>管理员</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="员工姓名" prop="sn"><el-input v-model="editForm.username" auto-complete="off"></el-input></el-form-item>
				<el-form-item label="员工邮箱" prop="sn"><el-input v-model="editForm.email" auto-complete="off"></el-input></el-form-item>
				<el-form-item label="员工电话" prop="sn"><el-input v-model="editForm.phone" auto-complete="off"></el-input></el-form-item>
				<el-form-item label="员工彦值" prop="sn"><el-input v-model="editForm.salt" auto-complete="off"></el-input></el-form-item>
				<el-form-item label="员工密码" prop="sn"><el-input v-model="editForm.password" auto-complete="off"></el-input></el-form-item>
				<el-form-item label="员工年龄" prop="sn"><el-input v-model="editForm.age" auto-complete="off"></el-input></el-form-item>

				<el-form-item label="员工状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="所属部门" >
					<el-select v-model="editForm.department"  value-key="id" placeholder="请选择">
						<el-option
								v-for="dept in departments"
								:key="dept.id"
								:label="dept.name"
								:value="dept">
							<span style="float: left">{{dept.name}}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{dept.sn}}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="权限">
					<el-radio-group v-model="editForm.logininfo">
						<el-radio class="radio" :label="1">用户</el-radio>
						<el-radio class="radio" :label="0">管理员</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="所属店铺">
					<!--<el-input v-model="editForm.manager"></el-input>-->
					<el-select v-model="editForm.shop"  value-key="id" placeholder="请选择">
						<el-option
								v-for="sh in shops"
								:label="sh.name"
								:value="sh">
							<span style="float: left">{{ sh.name }}</span>
							<!--<span style="float: right; color: #8492a6; font-size: 13px">{{ dept.phone }}</span>-->
						</el-option>
					</el-select>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<!--<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="addForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="addForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>-->
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, editEmployee, addEmployee } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
				employees: [],
                departments: [],
                shops:[],
                logins:[],
                total:0,
                title:"",
                currentPage: 1,
                pageSize:5,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
                    username: '',
                    email:'',
                    phone:'',
                    salt: '',
                    password: '',
                    age:null,
                    state:null,
                    shop:{},
                    department:{},
                    logininfo:{},
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},

			}
		},
		methods: {
		    /*获取所有部门信息,交给一个字段保存*/
		    getDepartments(){
				this.$http.get("/dept")
					.then(result=>{
					    this.departments = result.data
					}).catch(result=>{
					    alert("系统错误")
				})
			},
			formatSex: function (row, column) {
                return row.logininfo.type == true ? '否' : row.logininfo.type == false ? '是' : '未知';
            },
			getShops(){
		      this.$http.get("/shop")
				  .then(result=>{
				      this.shops = result.data
				  }).catch(result=>{
                     alert("系统错误")
			  })
			},
			getLogins(){
		      this.$http.get("/log")
				  .then(result=>{
				      this.logins=result.data
				  }).catch(result=>{
                  alert("系统错误")
			  })
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getEmployees();
			},
            /*高级查询：当查询时把页数设置为1在进行查询*/
            changePage(){
                this.currentPage = 1;
                this.getEmployees();
            },
			//获取用户列表:通过分页查询
			getEmployees() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword:this.filters.keyword
                };
                this.$http.post("/emp",para)
                    .then(result=>{
                        console.log("高级查询:",result)
                        result = result.data
                        //console.log("员工测试",result.data)
                        this.total = result.count
                        this.employees=result.data
                    }).catch(result=>{
                    alert("操作错误")
                })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
                    /*发送delete请求到后台*/
                    this.$http.delete("/emp/"+row.id)
                        .then(result=>{
                            /*关闭忙态框框*/
                            this.listLoading = false;
                            //console.log("单条删除：",result)
                            if(result.data.success){
                               /* alert(1)*/
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            }else {
                                alert(2)
                                this.$message({
                                    message: '删除失败',
                                    type: 'success'
                                });
                            }
                            this.getEmployees()
                        }).catch(result=>{
                        alert("系统异常")
                    })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
                this.title="编辑";
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
                this.editFormVisible = true;
				this.editForm = {
					username: '',
					email:'',
					phone:'',
					salt: '',
					password: '',
					age:null,
					state:1,
                    department:{},
                    logininfo:{},
                    shop:{},
				};
				this.title="添加"
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
                            /*var arr = this.editForm.parent/!*这是一个数组[2,5]*!/
                            /!*加上一个判断，判断添加部门是个添加了上级部门*!/
                            if(arr.length != null){//当添加了上级部门的时候
                                /!*取出最后一个值变为数组，注意是拷贝的对象中*!/
                                para.parent = {"id":arr[arr.length-1]}
                            }*/

                            this.$http.put("/emp",para)
                                .then(result=>{
                                    /*关闭模态框*/
                                    this.editFormVisible = false;
                                    /*关闭忙态框*/
                                    this.editLoading = false;
                                    if(result.data.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                    }else {
                                        this.$message({
                                            message: '提交失败',
                                            type: 'success'
                                        });
                                    }
                                    /*刷新页面数据*/
                                    this.getEmployees()
                                }).catch(result=>{
                                alert("系统错误")
                            })




						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							addEmployee(para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getEmployees();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/emp",ids)
						.then(result=>{
                            this.listLoading = false;
							//console.log(result.data)
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            }else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'success'
                                });
                            }
                            this.getEmployees();
						}).catch(result=>{
							alert("系统异常")
						})
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getEmployees();
			this.getDepartments();
			this.getLogins();
			this.getShops();
		}
	}

</script>

<style scoped>

</style>